import cv2
import tkinter as tk
from tkinter import ttk, filedialog
from PIL import Image, ImageTk

# 初始化变量
original_image = None
threshold_value = 127
binary_mode = cv2.THRESH_BINARY
canvas_width = 670
canvas_height = 400


# 导入图像函数
def load_image():
    global original_image
    file_path = filedialog.askopenfilename()
    if file_path:
        original_image = cv2.imread(file_path, cv2.IMREAD_GRAYSCALE)
        update_image(threshold_value)


# 更新图像函数
def update_image(threshold):
    if original_image is not None:
        # 等比缩放图像为画布大小
        resized_image = cv2.resize(original_image, (canvas_width, canvas_height))

        _, binary_image = cv2.threshold(resized_image, threshold, 255, binary_mode)
        img = Image.fromarray(binary_image)
        img_tk = ImageTk.PhotoImage(image=img)
        label.config(image=img_tk)
        label.image = img_tk
        threshold_label.config(text=f"当前阈值: {threshold_value}")


# 更新阈值函数
def update_threshold(val):
    global threshold_value
    threshold_value = int(val)
    update_image(threshold_value)


# 切换二值化模式
def set_threshold_mode(mode):
    global binary_mode
    if mode == "简单":
        binary_mode = cv2.THRESH_BINARY
    elif mode == "反向":
        binary_mode = cv2.THRESH_BINARY_INV
    elif mode == "截断":
        binary_mode = cv2.THRESH_TRUNC
    elif mode == "阈值到零":
        binary_mode = cv2.THRESH_TOZERO
    elif mode == "阈值到零反向":  # 第五种模式
        binary_mode = cv2.THRESH_TOZERO_INV
    update_image(threshold_value)


# 创建 Tkinter 窗口
root = tk.Tk()
root.title("阈值调整器")
root.geometry("700x470")  # 设置窗口大小

# 创建固定大小的画布
canvas = tk.Canvas(root, width=canvas_width, height=canvas_height)
canvas.pack(padx=10, pady=10)

label = ttk.Label(canvas)
canvas.create_window(0, 0, anchor='nw', window=label)

# 创建控件框架
controls_frame = ttk.Frame(root)
controls_frame.pack(side='bottom', fill='x', padx=10, pady=10)

# 创建导入按钮
load_button = ttk.Button(controls_frame, text="选择图像", command=load_image)
load_button.pack(side='left', padx=5)

# 创建二值化模式选择
mode_label = ttk.Label(controls_frame, text="二值化模式:")
mode_label.pack(side='left', padx=5)

modes = ["简单", "反向", "截断", "阈值到零", "阈值到零反向"]  # 添加第五种模式
mode_var = tk.StringVar(value=modes[0])

for mode in modes:
    rb = ttk.Radiobutton(controls_frame, text=mode, variable=mode_var, value=mode,
                         command=lambda m=mode: set_threshold_mode(m))
    rb.pack(side='left')

# 创建阈值选择的 Spinbox
threshold_spinbox = ttk.Spinbox(controls_frame, from_=0, to=255, increment=1, width=10,
                                command=lambda: update_threshold(threshold_spinbox.get()))
threshold_spinbox.set(threshold_value)
threshold_spinbox.pack(side='left', padx=5)

# 创建阈值显示标签
threshold_label = ttk.Label(controls_frame, text=f"当前阈值: {threshold_value}")
threshold_label.pack(side='left', padx=5)

# 运行 Tkinter 主循环
root.mainloop()
